package org.example.rowing.controller;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.FormatterUtil;
import org.example.rowing.domain.Race;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.enums.GenderEnum;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.service.RaceInfoService;
import org.example.rowing.service.TeamInfoService;
import org.example.rowing.vo.EventVO;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.TeamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class UpdateRaceController {
    @FXML
    public TextField distanceField;
    @FXML
    public ComboBox<String> raceTypeField;
    @FXML
    public ComboBox<String> genderField;
    @FXML
    public TextField firstScoreField;
    @FXML
    public TextField secondScoreField;
    @FXML
    public TextField thirdScoreField;
    @FXML
    public TextField forthScoreField;
    @FXML
    public TextField fifthScoreField;
    @FXML
    public TextField sixthScoreField;
    @FXML
    public TextField seventhScoreField;
    @FXML
    public TextField eighthScoreField;
    @FXML
    public RadioButton longDistanceYes;
    @FXML
    public RadioButton longDistanceNo;
    @FXML
    private TextField nameField;
    @FXML
    public ComboBox<String> eventNameField;
    @FXML
    private DatePicker dateField;
    @FXML
    private Label popupTitle;
    private RaceVO raceToEdit;
    private Map<String, Long> eventNameToIdMap = new HashMap<>();

    @Autowired
    private RaceInfoService raceInfoService;
    @Autowired
    private EventInfoService eventInfoService;


    // 用于在弹出框初始化时设置事件信息（用于编辑）
    public void initialize(RaceVO race) {
        // 限制输入只能为数字
        FormatterUtil.setIntegerOnly(distanceField);

        if (race != null) {
            this.raceToEdit = race;
            popupTitle.setText("修改比赛项目");
            nameField.setText(race.getName());
            dateField.setValue(LocalDate.parse(race.getRaceDate()));
            distanceField.setText(String.valueOf(race.getDistance()));

            Race selectedRaceById = raceInfoService.selectRaceById(race.getId());
            firstScoreField.setText(String.valueOf(selectedRaceById.getFirstScore()));
            secondScoreField.setText(String.valueOf(selectedRaceById.getSecondScore()));
            thirdScoreField.setText(String.valueOf(selectedRaceById.getThirdScore()));
            forthScoreField.setText(String.valueOf(selectedRaceById.getForthScore()));
            fifthScoreField.setText(String.valueOf(selectedRaceById.getFifthScore()));
            sixthScoreField.setText(String.valueOf(selectedRaceById.getSixthScore()));
            seventhScoreField.setText(String.valueOf(selectedRaceById.getSeventhScore()));
            eighthScoreField.setText(String.valueOf(selectedRaceById.getEighthScore()));

            // 设置长距离比赛单选按钮
            if (race.getIsLongDistance()) {
                longDistanceYes.setSelected(true);
            } else {
                longDistanceNo.setSelected(true);
            }

            // 根据给定的内容设置 raceTypeField 的默认选项
            raceTypeField.setItems(FXCollections.observableArrayList("单人", "双人", "四人", "八人"));
            raceTypeField.setValue(race.getRaceType());  // 选择传入的 raceType
            genderField.setItems(FXCollections.observableArrayList("男子","女子","混合"));
            genderField.setValue(race.getGenderEnum().getDisplayName());
            loadEventNames();
            eventNameField.setValue(race.getEventVO().getName());
        } else {
            popupTitle.setText("添加比赛项目");
            raceTypeField.setItems(FXCollections.observableArrayList("单人", "双人", "四人", "八人"));
            genderField.setItems(FXCollections.observableArrayList("男子","女子","混合"));
            loadEventNames();
            longDistanceNo.setSelected(true);
            this.raceToEdit = null;
        }
    }

    private void loadEventNames() {
        List<EventVO> eventVOS = eventInfoService.showEventsByType(BoatTypeEnum.ROWING);
        List<String> eventNames = new ArrayList<>();
        eventNameToIdMap.clear();
        for (EventVO eventVO : eventVOS) {
            eventNames.add(eventVO.getName());
            eventNameToIdMap.put(eventVO.getName(), eventVO.getId());
        }
        eventNameField.setItems(FXCollections.observableArrayList(eventNames));
    }

    // 保存赛事
    @FXML
    private void handleSaveEvent() {
        String raceName = nameField.getText();
        LocalDate raceDate = dateField.getValue();
        String distance = distanceField.getText();
        String raceType = raceTypeField.getValue();
        String gender = genderField.getValue();
        String eventName = eventNameField.getValue();
        String firstScore = firstScoreField.getText();
        String secondScore = secondScoreField.getText();
        String thirdScore = thirdScoreField.getText();
        String forthScore = forthScoreField.getText();
        String fifthScore = fifthScoreField.getText();
        String sixthScore = sixthScoreField.getText();
        String seventhScore = seventhScoreField.getText();
        String eighthScore = eighthScoreField.getText();
        boolean isLongDistance = longDistanceYes.isSelected();

        if (eventName == null || raceDate == null || raceName.isEmpty() || distance.isEmpty() ||
                raceType == null || gender == null) {
            log.warn("请填写完整的比赛信息");
            showErrorDialog("请填写完整的信息");
            return;
        }

        Long eventId = eventNameToIdMap.get(eventName);
        if (eventId == null) {
            log.error("赛事信息未找到，无法保存该信息");
            showErrorDialog("赛事信息未找到");
            return;
        }

        Race race = new Race(null, raceName, eventId, Integer.valueOf(distance), raceType,
                GenderEnum.fromDisplayName(gender), raceDate.toString(), Integer.valueOf(firstScore),
                Integer.valueOf(secondScore), Integer.valueOf(thirdScore), Integer.valueOf(forthScore),
                Integer.valueOf(fifthScore), Integer.valueOf(sixthScore), Integer.valueOf(seventhScore),
                Integer.valueOf(eighthScore), false, isLongDistance);

        if (raceToEdit == null) {
            // 添加赛事
            log.info("添加新比赛: {}", race);
        } else {
            // 修改赛事
            race.setId(raceToEdit.getId());  // 保持修改的赛事ID
            Race raceById = raceInfoService.selectRaceById(raceToEdit.getId());
            race.setIsFinished(raceById.getIsFinished());
            race.setIsLongDistance(raceById.getIsLongDistance());
            log.info("修改比赛: {}", race);
        }
        raceInfoService.saveOrUpdateRace(race);

        // 关闭弹窗
        closeWindow();
    }

    // 取消操作，关闭弹出框
    @FXML
    private void handleCancel() {
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) eventNameField.getScene().getWindow();
        stage.close();
    }

    // 弹出错误提示框
    private void showErrorDialog(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("输入错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
